<?php

class RegistrationsController extends AppController{

	var $helpers = array('Html', 'Form');
//	var $components = array('Auth', 'Cookie', 'Session');
	var $uses = array('Registration', 'EventDate');
	var $scaffold;

	function beforeFilter() {

		$this->Auth->allow('display', 'editRegistration', 'addEventxx');
		parent::beforeFilter();
	}

	function displaysingle($id = null){
		if (empty($this->data)) {
			$sFilter = " user_id = '$id' ";
			$this->data = $this->Registration->find($sFilter);
		} else {
				$this->Registration->save($this->data);
				debug($this->Registration->validationErrors);
		}
	}

	function display($id = null){
		$sFilter = " user_id = '$id' ";
		$this->set('aData', $this->Registration->findAll($sFilter, null, null, null, null, 3));
	}

	function addEvent($event_date_id = null, $nUnit = null){

		$user_id = $this->authUser['id'];

		// get Event price/category
		$sFilter  = " EventDate.id = '$event_date_id' ";
		$oEvent = $this->EventDate->find($sFilter);

		$nPrice = $oEvent['Event']['nPrice'];
		$category_id = $oEvent['Event']['category_id'];

			// create new registration object
		$data = array('Registration' => array());
		$data['Registration']['id'] = '';
		$data['Registration']['user_id'] = $user_id;
		$data['Registration']['event_date_id'] = $event_date_id;
		$data['Registration']['unit'] = $nUnit;
		$data['Registration']['price'] = $nPrice;


			// check if an unconfirmed event_date/user combination allready exists
			// in that case update existing line
		$sFilter  = " user_id = '$user_id' AND ";
		$sFilter .= " event_date_id = '$event_date_id' AND ";
		$sFilter .= " Registration.confirmed = '0' ";
		$oOldRegistration = $this->Registration->find($sFilter);
		if(!empty($oOldRegistration)){
			$data['Registration']['id'] = $oOldRegistration['Registration']['id'];
			$data['Registration']['unit'] += $oOldRegistration['Registration']['unit'];
		}

		$this->Registration->save($data);
		$pathCallback = '/controller/index/events/'.$category_id; // refactor: root
		$this->redirect($pathCallback);
	}

	function editRegistration($id = null){ // refactor: validation does not work/is not displayed in view
		if (empty($this->data)) {
			$sFilter = " user_id = '$id' ";
			$this->data = $this->Registration->findAll($sFilter);
		} else {
			$lsInvalidRegistrations = array();
			foreach($this->data as $index => $registration) {
				$this->Registration->create();
				$this->Registration->set($registration);
				if($this->Registration->validates()){
					$this->Registration->save($registration);
				} else {
					$lsInvalidRegistrations[$index] = $this->Registration->validationErrors;
					unset($this->Registration->validationErrors);
				}
			}
		}
			if (!empty($lsInvalidRegistrations)) {
				$this->Registration->validationErrors = $lsInvalidRegistrations;
			}
	}




}
?>


